package top.jandmla.excel.service.serviceImpl;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.jdbc.JDBCDataStore;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.jandmla.excel.pojo.User;
import top.jandmla.excel.configParam.UserBuilder;
import top.jandmla.excel.service.ShapService;
import top.jandmla.excel.util.FileUpload;
import top.jandmla.excel.util.shpIntoDB.ImportShpTools;
import top.jandmla.excel.util.unzipUtils.Unzip;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ShapServiceImpl implements ShapService {
    @Override
    public String startImport(MultipartFile mfile) {

        //转换文件类型
        File upLoadFile = FileUpload.getFileByMultipartFile(mfile);

        User user = new UserBuilder()
                .setFile(upLoadFile)
                .builder();
        assert upLoadFile != null;
        String filePath = upLoadFile.getPath();

        JDBCDataStore conn = ImportShpTools.getDataStore(user);
        List<SimpleFeatureSource> sources = null;
        List<File> list = null;
        try {

            //判断是压缩包后处理
            if (StringUtils.endsWith(filePath, ".zip")) {
                list = Unzip.unZipToFile(filePath, FileUtils.getTempDirectoryPath());
                List<File> shpList = list.stream().filter(s -> StringUtils.endsWith(s.getName(), ".shp"))
                        .collect(Collectors.toList());
                sources = ImportShpTools.readSHP(shpList);

                //判断是shp文件后处理
            } else if (StringUtils.endsWith(filePath, ".shp")) {
                sources = ImportShpTools.readSHP(filePath);
            }

            //如果找到文件就执行插入
            if (sources != null) {
                sources.forEach(feature -> {
                    JDBCDataStore dataStore = ImportShpTools.createTable(conn, feature, "");
                    ImportShpTools.writeShp2DataBin(dataStore, feature);
                });
                return "数据插入成功！！";
            } else
                return "数据插入失败！";
        } catch (Exception e) {
            e.printStackTrace();
            return "数据插入失败！";
        } finally {

            //若是解压文件，则删除解压出来的文件
            if (list != null) {
                Unzip.deleteFiles(list);
            }
        }
    }
}
